package com.zl.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.zl.common.Result;
import com.zl.common.VerifyCodeResult;
import com.zl.security.AuthenticationInfo;
import com.zl.security.AuthorizationUser;
import com.zl.security.JwtUser;
import com.zl.security.SecurityUtils;
import com.zl.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 授权、根据token获取用户详细信息
 */
@Slf4j
@RestController
@RequestMapping("auth")
public class AuthenticationController {

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    @Qualifier("jwtUserDetailsService")
    private UserDetailsService userDetailsService;

    /**
     * 登录授权
     * @param authorizationUser
     * @return
     */
    @PostMapping(value = "/login")
    public Result login(@Validated @RequestBody AuthorizationUser authorizationUser){

        // 查询验证码  清除验证码
        String code = LocalCacheUtil.removeAndGet(authorizationUser.getUuid());
        if (StringUtils.isBlank(code)) {
            return Result.error("验证码已过期");
        }
        if (StringUtils.isBlank(authorizationUser.getCode()) || !authorizationUser.getCode().equalsIgnoreCase(code)) {
            return Result.error("验证码错误");
        }
        JwtUser jwtUser = null;
        try {
            jwtUser = (JwtUser) userDetailsService.loadUserByUsername(authorizationUser.getUsername());
        } catch (Exception e) {
            log.error("登录异常：{}", Exceptions.getStackTraceAsString(e));
        }

        if(!jwtUser.getPassword().equals(EncryptUtils.encryptPassword(authorizationUser.getPassword()))){
            return Result.error("密码错误");
        }

        if(!jwtUser.isEnabled()){
            return Result.error("账号已停用，请联系管理员");
        }

        // 生成令牌
        final String token = jwtTokenUtil.generateToken(jwtUser);

        // 返回 token
        return Result.success(new AuthenticationInfo(token,jwtUser));
    }

    /**
     * 获取用户信息
     * @return
     */
    @RequestMapping(value = "userinfo")
    //@PreAuthorize("hasAnyRole('ADMIN')")
    public Result getUserInfo(){
        JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
        return Result.success(jwtUser);
    }

    /**
     * 获取验证码
     */
    @GetMapping(value = "vCode")
    public Result getCode(HttpServletResponse response) throws IOException {

        //生成随机字串
        String verifyCode = VerificationCodeUtil.generateVerifyCode(4);
        String uuid = IdUtil.simpleUUID();
        LocalCacheUtil.put(uuid,verifyCode, 120);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerificationCodeUtil.outputImage(w, h, stream, verifyCode);
        try {
            return Result.success(new VerifyCodeResult(Base64.encode(stream.toByteArray()),uuid));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            stream.close();
        }
    }
}
